#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define MAX_DATA_LEN 256
#define DELAY_TIME 1

int main()
{
    pid_t pid;
    char buf[MAX_DATA_LEN];
    const char *data = "Pipe Test";
    int real_read,real_write;
    int pipe_fd[2];

    memset((void*)buf, 0, sizeof(buf));
    /* 创建管道 */
    if(pipe(pipe_fd) < 0){
        perror("Pipe create error!\n");
        exit(1);
    }
        
    if ((pid=fork()) < 0) {
        perror("Fork error!\n");
        exit(1);
    } else if (pid == 0) {
        close(pipe_fd[1]); //子进程关闭写描述符，并通过使子进程暂停DELAY_TIME * 3（3秒）等待父进程已关闭相应的读描述符 */
        sleep(DELAY_TIME * 3);
        /* 子进程读取管道内容 */
        if ((real_read=read(pipe_fd[0], buf,MAX_DATA_LEN)) > 0) { 
            printf("Child receive %d bytes from pipe: '%s'.\n", real_read, buf);
        }
        close(pipe_fd[0]); //关闭子进程读描述符
        exit(0);
    } else {
        close(pipe_fd[0]); //父进程关闭读描述符，并通过使父进程暂停DELAY_TIME （1秒）等待子进程已关闭响应的写描述符
        sleep(DELAY_TIME);
        if ((real_write=write(pipe_fd[1],data,strlen(data))) > 0) {
            printf("Parent write %d bytes into pipe: '%s'.\n", real_write, data);
        }
        close(pipe_fd[1]);
        waitpid(pid, NULL, 0);
        exit(0);
    }
}